﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using WaterRegimenMonitor.Common;
using WaterRegimenMonitor.Web.Domain;

namespace WaterRegimenMonitor.Web.Code
{
    /// <summary>
    /// HTTP错误编码。
    /// </summary>
    public enum HttpErrorCode
    {
        //需要重定向执行登陆
        Unauthenticated = 516,
        //需要显示未登陆消息
        Unauthorized = 518,
        //显示普通异常消息
        CommonError = 520
    }

    /// <summary>
    /// Josn请求处理错误处理特性
    /// </summary>
    /// <remarks></remarks>
    public class JsonHandleErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 当发生异常时调用。
        /// </summary>
        /// <param name="filterContext">操作-筛选器上下文。</param>
        /// <remarks></remarks>
        public override void OnException(ExceptionContext exceptionContext)
        {
            //判定是否发生异常
            if (exceptionContext.Exception != null)
            {
                //用于保存错误提示信息
                string errorMessage = null;

                //用于保存错误码
                int errorCode = 0;

                //判断是否为未登录异常
                if (exceptionContext.Exception is UnauthenticatedException)
                {
                    errorCode = (int)HttpErrorCode.Unauthenticated;
                    errorMessage = "您尚未登录系统，请登录系统之后重试。";
                }
                //判断是否未未授权异常
                else if (exceptionContext.Exception is UnauthorizedException)
                {
                    errorCode = (int)HttpErrorCode.Unauthorized;
                    errorMessage = "您尚未授权浏览此信息，请联系系统管理员获得访问权限。";
                }
                //判断是否为未知异常
                else
                {
                    errorCode = (int)HttpErrorCode.CommonError;
#if DEBUG
                    errorMessage = exceptionContext.Exception.ToString();
#else
                    errorMessage = "系统出错，请稍后再试。";
#endif
                }

                //设置返回吗
                exceptionContext.HttpContext.Response.StatusCode = errorCode;
                //创建异常返回结果
                exceptionContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new JsonResultViewModel
                    {
                        success = false,
                        code = errorCode,
                        message = errorMessage
                    }
                };

                //设置为当前HTTP请求启用自定义错误。
                exceptionContext.HttpContext.Response.TrySkipIisCustomErrors = true;

                //设置异常已经被处理
                exceptionContext.ExceptionHandled = true;
            }
        }
    }
}
